import java.nio.ByteBuffer;

import jpcap.packet.Packet;


public class dataPacket_builder extends Packet{

	private short dns_TransactionID;
	private short dns_flag;
	private short dns_question;
	private short dns_answer_RRS;
	private short dns_authority_RRS;
	private short dns_Additional_RRS;
	private short dns_host_type;
	private short dns_class;
	/**
	 *Sends a DNS Request
	 * @param request
	 * @return
	 */
	public byte[] dnsRequest(String request)
	{	
		int buffersize = 18+request.length();
		ByteBuffer dnsBB = ByteBuffer.allocate(buffersize);
		dns_TransactionID = randomTransIDGenerator();
		dns_flag =256; //hex : 0x0100
		dns_question = 1;
		dns_answer_RRS = 0;
		dns_authority_RRS = 0;
		dns_Additional_RRS = 0;
		dns_host_type = 1;
		dns_class = 1;
		dnsBB.putShort(dns_TransactionID);
		dnsBB.putShort(dns_flag);
		dnsBB.putShort(dns_question);
		dnsBB.putShort(dns_answer_RRS);
		dnsBB.putShort(dns_authority_RRS);
		dnsBB.putShort(dns_Additional_RRS);		
		dnsBB.put(data_Interpreter(request));
		dnsBB.putShort(dns_host_type);
		dnsBB.putShort(dns_class);
		dnsBB.rewind();
		return dnsBB.array();		
	}
	/**
	 * Generates a random Transaction ID
	 * @return
	 */
	short randomTransIDGenerator(){
		return (short)(Math.random() * (65535 - 0) + 0);
	}
	/**
	 * Converts the DNS Request Data into bytes
	 * @param request
	 * @return
	 */
	byte[] data_Interpreter(String request)
	{
		String[] fields = request.split("\\.");		
		int bufferlength = request.length()+2;
		ByteBuffer interpret = ByteBuffer.allocate(bufferlength);
		for(int i=0;i<fields.length;i++)
		{			
			interpret.put((byte) fields[i].length());	//The length of the string
			interpret.put(fields[i].getBytes());			//The String
		}
		interpret.put((byte) 0);
		interpret.rewind();
		return interpret.array();
	}
}
